import React, {Component} from 'react';
import {Table, Pagination, Loading} from '@icedesign/base';
import IceContainer from '@icedesign/container';
import TableFilter from './TableFilter';
import {getTableData} from '../../../../api/index'
import DataBinder from '@icedesign/data-binder';
import EditDialog from "./EditDialog";
import DeleteBalloon from "./DeleteBalloon";
import CustomTable from './CustomTable'

export const NameMap = {
  'STA_ID': 'STA_ID',
  'YMonth': '年份',
  'ORG1_NAME': '站点1名称',
  'DeviceTypeName': '驱动类型名字',
  'ORG2_NAME': '站点2名称',
  'DeviceType': '驱动类型'
};


@DataBinder({ // todo 必须和下面的 组件类 挨着写
  SendData: { // SendData 是 key, 区别不同
    url: '/api/TableData',
    method: 'post',
    data: {       // todo 发送参数的格式
      current: 1,
      pageSize: 10,
      years: [],
      deviceType: [],
    },
    defaultBindingData: { // todo 这里是 接口返回数据的格式
      status: 200,
      statusText: 'ok',
      data: {
        ListResult: [],
        current: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  updateData: { // UpdateData 是 key, 区别不同
    url: '/api/updateData',
    method: 'post',
    data: {       // todo 发送参数的格式
      id: 0,
      values: {
        DeviceType: "1",
        DeviceTypeName: "信阳驼峰站",
        ORG1_ID: "103",
        ORG1_NAME: "信阳电务段",
        ORG2_ID: "103009",
        ORG2_NAME: "检修车间",
        ORG3_ID: "103009001",
        ORG3_NAME: "计量工区",
        STA_ID: "0107aa96ec0549748be15207123c261a",
        STA_NAME: "信阳驼峰站",
        Total_Appraisal: 0,
        Total_DEV: 195,
        Total_Fine: 0,
        Total_Good: 0,
        Total_Qualified: 0,
        Total_UnQualified: 0,
        YMonth: "2018"
      }
    },
    success: (res, defaultCallback, originResponse) => {
      console.log('请求成功了，返回的数据为', res)
      console.log("orginResponse",originResponse)
      // 执行默认的逻辑请求成功逻辑
      // 通常为弹出反馈 Toast
      if (res.status == 200) {
        alert("data update success")
      } else {
        alert("data update fail")
      }
      defaultCallback(); // 没有找到是哪里执行
      // originResponse 内容请参见：https://github.com/axios/axios#response-schema
    },
    error: (res, defaultCallback, originResponse) => {
      console.log("err",'res', res, originResponse);
      alert("data update fail",originResponse.statusText)
      defaultCallback();
    },
    defaultBindingData: { // todo 这里是 接口返回数据的格式
      status: 200,
      statusText: 'ok',
      data: {
        ListResult: [],
        current: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  delData: { //  key, 区别不同
    url: '/api/delData',
    method: 'post',
    data: {       // todo 发送参数的格式
      id: 0,
    },
    defaultBindingData: { // todo 这里是 接口返回数据的格式
      status: 200,
      statusText: 'ok',
      // data: {
      //   ListResult: [],
      //   current: 1,
      //   total: 0,
      //   pageSize: 10
      // }
    }
  }
})

export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    // let page = {current: 1, pageSize: 10, years: [], deviceType: []};
    this.state = { // 默认分页数据
      current: 1,
      pageSize: 10,
      data: {},
      years: [],
      deviceType: []
    }

    this.columns = [
      {
        title: 'STA_ID',
        dataIndex: 'STA_ID',
        key: 'STA_ID',
      },
      {
        title: NameMap['YMonth'],
        dataIndex: 'YMonth',
        key: 'YMonth',
      },
      {
        title: '站点1名称',
        dataIndex: 'ORG1_NAME',
        key: 'ORG1_NAME',
      },
      {
        title: '驱动类型名字',
        dataIndex: 'DeviceTypeName',
        key: 'DeviceTypeName',
      },
      {
        title: '站点2名称',
        dataIndex: 'ORG2_NAME',
        key: 'ORG2_NAME',
      },
      {
        title: '驱动类型',
        dataIndex: 'DeviceType',
        key: 'DeviceType',
      },
      {
        title: '操作',
        key: 'action',
        render: (value, index, record) => {
          // console.log(value, index, record) // value: 不清楚false， index是数组序号 0，  record是一条数据，{id: 1, YMonth: "2018", DeviceType: "106100", STA_NAME: "信阳驼峰站", ORG1_ID: "103", …}
          return (
            <span>
              <EditDialog
                // index={index}
                index={record.id} // id值方便回传
                record={record}
                updateFormValues={this.updateFormValues} // todo 绑定弹窗的方法
              />
              <DeleteBalloon
                handleRemove={() => this.handleRemove(value, index, record)}
              />
            </span>
          );
        },
      },
    ];
  }

  handleRemove = (value, index, record) => {
    console.log(value, index, record)
    this.props.updateBindingData('delData', {
      data: {
        id: record.id,
        // values:values,
        // state:{...this.state}
      }
    }, () => {
      this.props.updateBindingData('SendData', { // 更新完数据，callback 刷新数据
        data: {   // 发送参数
          current: 1,
          pageSize: this.state.pageSize,
          years: this.state.years,
          deviceType: this.state.deviceType,
        }
      }, function (res) {
        console.log(res)
        alert("data del success")
      });
    });
  };

  updateFormValues = (dataIndex, values) => {
    console.log(dataIndex, values)
    this.props.updateBindingData('updateData', {
      data: {
        id: dataIndex,
        values: values,
        // state:{...this.state}
      }
    }, (response) => {
      console.log(response)
      this.props.updateBindingData('SendData', { // 更新完数据，callback 刷新数据
        data: {   // 发送参数
          current: 1,
          pageSize: this.state.pageSize,
          years: this.state.years,
          deviceType: this.state.deviceType,
        }
      });
    });

  };

  RecvFormData({years, deviceType}) { // 组件通信
    console.log(years, deviceType);
    let y = []
    let d = []
    if (years == undefined || years == "") {
      y = []
    } else {
      y = []
      y.push(years)
    }
    if (deviceType == undefined || deviceType == "") {
      d = []
    } else {
      d = []
      d.push(deviceType)
    }
    this.setState({
      years: y,
      deviceType: d
    });
    this.props.updateBindingData('SendData', {
      data: {   // 发送参数
        current: 1,
        pageSize: this.state.pageSize,
        years: y,
        deviceType: d,
      }
    }, function (res) {
      console.log(res)
    });
  }

  componentDidMount() {
    // todo 使用databinder 默认数据第一次渲染，初始化第一页的数据

    // 使用DataBinder 中默认的 发送参数
    this.props.updateBindingData('SendData');
  }

  handlePaginationChange = (current) => { // 改变页码函数,current自动传入
    // this.setState({ // 页码保存
    //   current: current
    // });
    this.props.updateBindingData('SendData', {
      data: {   // 发送参数
        current: current,
        pageSize: this.state.pageSize,
        years: this.state.years,
        deviceType: this.state.deviceType,
      }
    });
  };

  handlePageSizeChange = (pagesize) => { // 改变显示个数
    this.setState({
      pageSize: pagesize // 显示个数保存
    });
    this.props.updateBindingData('SendData', {
      data: {   // 发送参数
        current: 1, // 显示的个数多以后 ，可能会没有超过当前页
        pageSize: pagesize,
        years: this.state.years,
        deviceType: this.state.deviceType,
      }
    });
  };


  renderOper = () => {
    return (
      <div>
        <a style={styles.link}>详情</a>
        <span style={styles.separator}/>
        <a style={styles.link}>申请权限</a>
      </div>
    );
  };

  render() {
    console.log(11111111, this.props.bindingData)
    const dataSource = this.props.bindingData.SendData; // SendData 是 binder方法的key
    console.log(22222222,dataSource);

    // todo CustomTable 是包装一层返回的table组件， 同时生成列头
    // Loading 加载动画
    return (
      <IceContainer style={styles.container}>
        <h4 style={styles.title}>测试数据</h4>
        <TableFilter filterData={this.RecvFormData.bind(this)}/>
        <Loading visible={dataSource.__loading} shape="fusion-reactor">
          <div>
            <CustomTable
              dataSource={dataSource.ListResult}
              columns={this.columns}
              hasBorder={false}
              isLoading={this.props.bindingData.__loading}
              // optimization={false}
            />

            <Pagination
              style={styles.pagination}
              current={dataSource.current}
              pageSizeSelector='filter'
              total={dataSource.total}
              pageSize={dataSource.pageSize}
              onChange={this.handlePaginationChange} // 点击页码的 函数
              onPageSizeChange={this.handlePageSizeChange}  // 点击每页显示多少的 函数
            />
          </div>
        </Loading>
      </IceContainer>
    );
  }
}

const styles = {
  container: {
    margin: '20px',
    padding: '0 0 20px',
  },
  title: {
    margin: '0',
    padding: '15px 20px',
    fonSize: '16px',
    textOverflow: 'ellipsis',
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    color: 'rgba(0,0,0,.85)',
    fontWeight: '500',
    borderBottom: '1px solid #eee',
  },
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 8px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    textAlign: 'right',
    marginRight: '20px',
  },
};
